import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { message } from 'antd';
import { isLocal } from '../utils';

let axiosInstance: AxiosInstance = axios.create({
  baseURL: '/',
  responseType: 'json',
  withCredentials: true,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json; charset=utf-8',
    'X-Requested-With': 'XMLHttpRequest',
  },
  validateStatus() {
    return true;
  },
});

axiosInstance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // const token = localStorage.token;
    // if (token) {
    //   Object.assign(config.headers, { authorization: `Bearer23 ${token}2` });
    // }
    return config;
  },
  (err: any) => {
    return Promise.reject(err);
  }
);
export const myAxios = axiosInstance;
axiosInstance.interceptors.response.use(
  (response: any) => {
    // console.log('拦截请求返回值', response);
    let data: any = response.data;
    if (response.status === 404) {
      message.error('服务器异常，请稍后');
      return Promise.reject(response);
    }
    if (data.status === true) {
      if (data.appCode === 200) {
        return Promise.resolve(data);
      } else if (
        data.appCode === 401 /*用户不存在*/ ||
        data.appCode === 403 /*没有权限*/ ||
        response.status === 401
      ) {
        if (isLocal()) {
          message.error('本地cookie过期需要更换新的！');
        } else {
          message.error(data.appMessage);
          //退出重新登录
          window.location.href = '/apis/logout';
        }
      } else {
        message.error(data.appMessage || '服务器异常，请稍后');
        return Promise.reject(response);
      }
    } else {
      message.error(data.appMessage || '服务器异常，请稍后');
      return Promise.reject(response);
    }
  },
  (err: any) => {
    return Promise.reject(err);
  }
);

export const axiosDownloadExcel = (options: AxiosRequestConfig<any>) => {
  axios({
    responseType: 'blob',
    ...options,
  })
    .then((response: any) => {
      // @ts-ignore
      const blob = new Blob([response.data], { type: response.data.type });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      const contentDisposition = response.headers['content-disposition'];
      let fileName = 'unknown';
      const fileNameMatch = contentDisposition?.match(/filename=(.+)/);
      if (fileNameMatch?.length === 2) {
        fileName = fileNameMatch[1];
      }
      link.setAttribute('download', decodeURIComponent(escape(fileName)));
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
    })
    .catch((err: any) => {
      // message.error("服务器异常");
      message.error(err.message);
    });
};
